package cn.lyd.org.service.impl;

import cn.lyd.basic.service.impl.BaseServiceImpl;
import cn.lyd.basic.util.Md5Utils;
import cn.lyd.basic.util.PageList;
import cn.lyd.basic.util.StrUtils;
import cn.lyd.org.domain.Department;
import cn.lyd.org.domain.Employee;
import cn.lyd.org.mapper.DepartmentMapper;
import cn.lyd.org.mapper.EmployeeMapper;
import cn.lyd.org.query.EmployeeQuery;
import cn.lyd.org.service.IEmployeeService;
import cn.lyd.user.domain.Logininfo;
import cn.lyd.user.mapper.LogininfoMapper;
import jdk.nashorn.internal.runtime.options.LoggingOption;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：员工
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;


    /**
     * 查部门树
     * @param
     * @return
     */
    @Override
    public List<Department> deptTree() {

        //=========部门树
        //1.查出所有的部门
        List<Department> departments = departmentMapper.findAll();
        //2.创建map集合---将key设为每个部门的id，val设置为id对应的部门
        Map<Long, Department> map = new HashMap<>();
        //3.遍历所有部门，装进map里
        for (Department department : departments){
            map.put(department.getId(),department);
        }
        //4.创建部门树集合
        List<Department> deptTree = new ArrayList<>();
        //5.遍历所有部门，判断该部门是顶级部门还是子部门，判断有没有父部门
        for (Department department: departments) {
            //5.1判断是不是顶级部门
            if (department.getParent_id()==null){
                //5.1.1是顶级部门，装进部门树
                deptTree.add(department);
            }else {
                //5.1.2不是顶级部门，看他的父部门是什么(通过父部门id，map集合获取)
                Long parent_id = department.getParent_id();
                Department parentDepartment = map.get(parent_id);

                //5.1.2.1如果父部门存在()，把这个部门加到父部门的子部门里
                if (parentDepartment!=null){
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        //返回部门树集合
        return deptTree;


    }


    @Override
    public void add(Employee employee) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        //创建Loginfo对象
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);//0：管理员
        logininfo.setDisable(true);//自增长id

        //将Logininfo_id设置到employee对象中
        employee.setLogininfo_id(logininfo.getId());
        //添加到数据库
        super.add(employee);
        //employeeMapper.add(employee);//效果同上

        //为当前员工添加角色信息
        if (employee.getRole_id()!=null){
            employeeMapper.addRole(employee);
        }

    }

    @Override
    public void del(Long id) {
       /*
        外键：关联字段 + 外键约束
        如果只有关联字段，没有约束可以随便删
        但是如果有关联字段，也有外键约束 - 先删除关联信息，再删除当前表的数据
        开发中：先添加关联字段，不添加外键约束。开发完成之后将约束条件加进去。-方便开发时测试
        */
        //删除角色信息---先删除中间表的信息（观察表字段 通过员工id删除角色）再删除员工信息
        employeeMapper.delEmployeeByEmployeeId(id);


        //查找employee对象
        Employee employee = employeeMapper.findById(id);
        //删除Logininfo信息
        logininfoMapper.del(employee.getLogininfo_id());
        //删除employee信息
        super.del(id);

    }

    @Override
    public void update(Employee employee) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        //查找到原来的employee对象
        Employee oldEmployee = employeeMapper.findById(employee.getId());
        employee.setLogininfo_id(oldEmployee.getLogininfo_id());
        employee.setShop_id(oldEmployee.getShop_id());

        //更新数据t_employee
        super.update(employee);

        //更新数据t_logininfo
        Logininfo oldLogininfo = logininfoMapper.findById(oldEmployee.getLogininfo_id());
        BeanUtils.copyProperties(employee,oldLogininfo);
        //属性同名原则会把员工的id拷贝给登录信息对象的id
        oldLogininfo.setId(oldEmployee.getLogininfo_id());
        logininfoMapper.update(oldLogininfo);


        //修改当前员工角色信息
        if (employee.getRole_id()!=null){
            //删除角色信息
            employeeMapper.delEmployeeByEmployeeId(employee.getRole_id());
            //再添加新的角色信息
            employeeMapper.addRole(employee);
        }
    }


    /**
     *批量删除
     * @param ids
     */
    @Override
    public void patchDel(Long[] ids) {
        for (Long id:ids) {
            del(id);
        }
    }
}
